package com.tsk.admin;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: 黄嘉振
 * @create: 2023/4/28 10:28
 * @description:
 **/
public class Example {
    private static AuthenticationManager am = new SampleAuthenticationManager();

    public static void main(String[] args) throws Exception {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

        while (true) {
            //模拟输入用户名密码
            System.out.println("Please enter your username:");
            String name = in.readLine();

            System.out.println("Please enter your password:");
            String password = in.readLine();

            try {
                //根据用户名/密码，生成未认证Authentication
                Authentication request = new UsernamePasswordAuthenticationToken(name, password);
                System.out.println("Authentication: " + request);
                //交给AuthenticationManager 认证
                Authentication result = am.authenticate(request);
                //将已认证的Authentication放入SecurityContext
                SecurityContextHolder.getContext().setAuthentication(result);
                break;
            } catch (AuthenticationException e) {
                System.out.println("Authentication failed: " + e.getMessage());
            }
        }

        System.out.println("Successfully authenticated. Security context contains: "
                + SecurityContextHolder.getContext().getAuthentication());
    }
}

//认证类
class SampleAuthenticationManager implements AuthenticationManager {
    //配置一个简单的用户权限集合
    static final List<GrantedAuthority> AUTHORITIES = new ArrayList<GrantedAuthority>();

    static {
        AUTHORITIES.add(new SimpleGrantedAuthority("ROLE_USER"));
    }

    public Authentication authenticate(Authentication auth) throws AuthenticationException {
        //如果用户名和密码一致，则登录成功，这里只做了简单认证
        if (auth.getName().equals(auth.getCredentials())) {
            //认证成功，生成已认证Authentication，比未认证多了权限
            return new UsernamePasswordAuthenticationToken(auth.getName(), auth.getCredentials(), AUTHORITIES);
        }

        throw new BadCredentialsException("Bad Credentials");
    }
}
